import { useState } from 'react';
import { Button } from '../components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import { Plus, BookOpen, Upload, Trash2, Search, FileText, Link, Database } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '../components/ui/dialog';
import { Input } from '../components/ui/input';
import { Label } from '../components/ui/label';
import { Textarea } from '../components/ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../components/ui/tabs';
import { toast } from '../hooks/use-toast';

interface KnowledgeItem {
  id: string;
  title: string;
  type: 'document' | 'url' | 'text';
  content?: string;
  url?: string;
  size?: number;
  createdAt: Date;
  tags: string[];
}

export default function KnowledgePage() {
  const [knowledgeItems, setKnowledgeItems] = useState<KnowledgeItem[]>([]);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [newItem, setNewItem] = useState({
    title: '',
    type: 'text' as const,
    content: '',
    url: '',
    tags: [] as string[],
  });

  const handleCreateItem = async () => {
    try {
      const item: KnowledgeItem = {
        id: Date.now().toString(),
        title: newItem.title,
        type: newItem.type,
        content: newItem.content,
        url: newItem.url,
        createdAt: new Date(),
        tags: newItem.tags,
      };
      
      setKnowledgeItems(prev => [...prev, item]);
      setIsCreateDialogOpen(false);
      setNewItem({
        title: '',
        type: 'text',
        content: '',
        url: '',
        tags: [],
      });
      
      toast({
        title: "Knowledge Item Created",
        description: `"${item.title}" has been added to your knowledge base.`,
      });
    } catch (error) {
      toast({
        title: "Error",
        description: "Failed to create knowledge item. Please try again.",
        variant: "destructive",
      });
    }
  };

  const handleDeleteItem = (itemId: string) => {
    setKnowledgeItems(prev => prev.filter(item => item.id !== itemId));
    toast({
      title: "Item Deleted",
      description: "Knowledge item has been removed from your knowledge base.",
    });
  };

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (files) {
      Array.from(files).forEach(file => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const item: KnowledgeItem = {
            id: Date.now().toString() + Math.random(),
            title: file.name,
            type: 'document',
            content: e.target?.result as string,
            size: file.size,
            createdAt: new Date(),
            tags: [],
          };
          setKnowledgeItems(prev => [...prev, item]);
        };
        reader.readAsText(file);
      });
      
      toast({
        title: "Files Uploaded",
        description: `${files.length} file(s) have been added to your knowledge base.`,
      });
    }
  };

  const filteredItems = knowledgeItems.filter(item =>
    item.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    item.content?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    item.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()))
  );

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'document':
        return <FileText className="h-4 w-4" />;
      case 'url':
        return <Link className="h-4 w-4" />;
      default:
        return <Database className="h-4 w-4" />;
    }
  };

  return (
    <div className="flex flex-col h-full p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Knowledge Base</h1>
          <p className="text-slate-600 dark:text-slate-400">
            Manage your documents, URLs, and text snippets for AI context
          </p>
        </div>
        
        <div className="flex gap-2">
          <input
            type="file"
            multiple
            accept=".txt,.md,.json,.csv"
            onChange={handleFileUpload}
            className="hidden"
            id="file-upload"
          />
          <Button variant="outline" onClick={() => document.getElementById('file-upload')?.click()}>
            <Upload className="h-4 w-4 mr-2" />
            Upload Files
          </Button>
          
          <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                Add Knowledge
              </Button>
            </DialogTrigger>
            <DialogContent className="sm:max-w-[500px]">
              <DialogHeader>
                <DialogTitle>Add Knowledge Item</DialogTitle>
                <DialogDescription>
                  Add text content or URLs to your knowledge base.
                </DialogDescription>
              </DialogHeader>
              <Tabs value={newItem.type} onValueChange={(value) => setNewItem({ ...newItem, type: value as any })}>
                <TabsList className="grid w-full grid-cols-2">
                  <TabsTrigger value="text">Text Content</TabsTrigger>
                  <TabsTrigger value="url">URL</TabsTrigger>
                </TabsList>
                
                <TabsContent value="text" className="space-y-4">
                  <div className="grid gap-2">
                    <Label htmlFor="title">Title</Label>
                    <Input
                      id="title"
                      value={newItem.title}
                      onChange={(e) => setNewItem({ ...newItem, title: e.target.value })}
                      placeholder="Enter title"
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="content">Content</Label>
                    <Textarea
                      id="content"
                      value={newItem.content}
                      onChange={(e) => setNewItem({ ...newItem, content: e.target.value })}
                      placeholder="Enter your text content"
                      rows={6}
                    />
                  </div>
                </TabsContent>
                
                <TabsContent value="url" className="space-y-4">
                  <div className="grid gap-2">
                    <Label htmlFor="url-title">Title</Label>
                    <Input
                      id="url-title"
                      value={newItem.title}
                      onChange={(e) => setNewItem({ ...newItem, title: e.target.value })}
                      placeholder="Enter title"
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="url">URL</Label>
                    <Input
                      id="url"
                      value={newItem.url}
                      onChange={(e) => setNewItem({ ...newItem, url: e.target.value })}
                      placeholder="https://example.com"
                    />
                  </div>
                </TabsContent>
              </Tabs>
              
              <div className="flex justify-end gap-2 mt-4">
                <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                  Cancel
                </Button>
                <Button onClick={handleCreateItem} disabled={!newItem.title}>
                  Add Item
                </Button>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Search */}
      <div className="mb-6">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-slate-400" />
          <Input
            placeholder="Search knowledge base..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-10"
          />
        </div>
      </div>

      {/* Knowledge Items */}
      <div className="flex-1 overflow-auto">
        {filteredItems.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-64 text-center">
            <BookOpen className="h-12 w-12 text-slate-400 mb-4" />
            <h3 className="text-lg font-semibold mb-2">
              {knowledgeItems.length === 0 ? "No Knowledge Items" : "No Results Found"}
            </h3>
            <p className="text-slate-600 dark:text-slate-400 mb-4">
              {knowledgeItems.length === 0 
                ? "Add documents, URLs, or text content to build your knowledge base."
                : "Try adjusting your search query."
              }
            </p>
            {knowledgeItems.length === 0 && (
              <Button onClick={() => setIsCreateDialogOpen(true)}>
                <Plus className="h-4 w-4 mr-2" />
                Add Your First Item
              </Button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {filteredItems.map((item) => (
              <Card key={item.id} className="hover:shadow-md transition-shadow">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-lg flex items-center gap-2">
                      {getTypeIcon(item.type)}
                      {item.title}
                    </CardTitle>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleDeleteItem(item.id)}
                      className="text-red-600 hover:text-red-700"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                  <CardDescription>
                    {item.type === 'url' ? item.url : 
                     item.content ? item.content.substring(0, 100) + '...' : 
                     'No content'}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div className="flex items-center gap-2">
                      <Badge variant="outline">{item.type}</Badge>
                      {item.size && (
                        <Badge variant="outline">
                          {(item.size / 1024).toFixed(1)} KB
                        </Badge>
                      )}
                    </div>
                    <div className="text-xs text-slate-500 dark:text-slate-400">
                      Added {item.createdAt.toLocaleDateString()}
                    </div>
                    {item.tags.length > 0 && (
                      <div className="flex flex-wrap gap-1">
                        {item.tags.map((tag, index) => (
                          <Badge key={index} variant="secondary" className="text-xs">
                            {tag}
                          </Badge>
                        ))}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}